<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 级联选择器区域 -->
      <p>
        选择商品分类：<el-cascader
          v-model="paramsCascaderValue"
          :options="GoodsCateData"
          :props="paramsCascaderProps"
          @change="paramsCascaderHandleChange"
        ></el-cascader>
      </p>

      <!-- Tabs切换区域 -->
      <el-tabs v-model="paramsActiveName" @tab-click="ParamsTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="addParamsBtn"
          >
            添加参数
          </el-button>
          <!-- 表格区域 -->
          <el-table :data="paramsManyData" style="width: 100%" border stripe>
            <!-- 折叠行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="item.attr_id"
                  closable
                  @close="paramsTagClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.paramsInputVisible"
                  v-model="scope.row.paramsInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="paramsHandleInputConfirm(scope.row)"
                  @blur="paramsHandleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="paramsEditBtn(scope.row)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsBtn(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only"
          ><el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="addParamsBtn"
            >添加属性</el-button
          >
          <!-- 表格区域 -->
          <el-table :data="paramsOnlyData" style="width: 100%" border stripe>
            <!-- 折叠行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="item.attr_id"
                  closable
                  @close="paramsTagClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.paramsInputVisible"
                  v-model="scope.row.paramsInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="paramsHandleInputConfirm(scope.row)"
                  @blur="paramsHandleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="paramsEditBtn(scope.row)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsBtn(scope.row)"
                ></el-button>
              </template>
            </el-table-column> </el-table
        ></el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/添加属性对话框 -->
    <el-dialog
      :title="'添加' + addParamsTitle"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogVisibleClose"
    >
      <el-form
        :model="addParamsDialogVisibleForm"
        label-width="100px"
        :rules="addParamsDialogVisibleFormRules"
        ref="addParamsDialogVisibleFormRef"
      >
        <el-form-item :label="addParamsTitle" prop="attr_name">
          <el-input v-model="addParamsDialogVisibleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数/静态属性对话框 -->
    <el-dialog
      :title="'修改' + addParamsTitle"
      :visible.sync="EditParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="editParamsDialogVisibleForm"
        label-width="100px"
        :rules="addParamsDialogVisibleFormRules"
        ref="editParamsDialogVisibleFormRef"
      >
        <el-form-item :label="addParamsTitle" prop="attr_name">
          <el-input v-model="editParamsDialogVisibleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器值
      paramsCascaderValue: [],
      // 级联选择器数据源
      GoodsCateData: [],
      // 级联选择器配置选项
      paramsCascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 绑定值，选中选项卡的 name
      paramsActiveName: 'many',
      // 动态参数数据
      paramsManyData: [],
      // 静态属性数据
      paramsOnlyData: [],
      // 控制添加参数/添加属性对话框显示隐藏
      addParamsDialogVisible: false,
      // 添加参数/添加属性对话框表单数据对象
      addParamsDialogVisibleForm: {
        attr_name: ''
      },
      // 添加参数/添加属性对话框表单验证规则
      addParamsDialogVisibleFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      //  修改动态参数/静态属性对话框
      EditParamsDialogVisible: false,
      // 修改动态参数/静态属性对话框表单数据对象
      editParamsDialogVisibleForm: {
        attrId: 0,
        attr_name: ''
      },
      // 文本输出框跟btn之间切换
      paramsInputVisible: false,
      //  文本输入框数据双向绑定
      paramsInputValue: ''
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    // 获取商品分类3级菜单
    async getGoodsCate() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      //   console.log(res)
      this.GoodsCateData = res.data
    },
    //  级联选择器发生改变触发
    paramsCascaderHandleChange() {
      if (this.paramsCascaderValue.length !== 3) {
        this.paramsCascaderValue = []
        this.paramsManyData = []
        this.paramsOnlyData = []
        return
      }
      // 获取动态参数/静态属性数据
      this.getTabsParams()
    },
    // tab 被选中时触发
    ParamsTabsClick() {
      if (this.paramsCascaderValue.length !== 3) {
        return
      }
      // 获取动态参数/静态属性数据
      this.getTabsParams()
    },
    // 获取动态参数/静态属性数据
    async getTabsParams() {
      const { data: res } = await this.$http.get(
        `categories/${this.getCateThreeID}/attributes`,
        {
          params: {
            sel: this.paramsActiveName
          }
        }
      )
      res.data.forEach(item => {
        item.attr_vals =
          item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        // 文本输出框跟btn之间切换
        item.paramsInputVisible = false
        //  文本输入框数据双向绑定
        item.paramsInputValue = ''
      })
      if (this.paramsActiveName === 'many') {
        this.paramsManyData = res.data
      } else {
        this.paramsOnlyData = res.data
      }
    },
    // 添加参数/添加属性按钮
    addParamsBtn() {
      // 显示添加参数/添加属性对话框
      this.addParamsDialogVisible = true
    },
    // 添加动态参数/添加属性
    addParams() {
      // 表单预验证
      this.$refs.addParamsDialogVisibleFormRef.validate(async vdate => {
        if (!vdate) return false
        const { data: res } = await this.$http.post(
          `categories/${this.getCateThreeID}/attributes`,
          {
            attr_name: this.addParamsDialogVisibleForm.attr_name,
            attr_sel: this.paramsActiveName
          }
        )
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        // 提示消息
        this.$message.success(res.meta.msg)
        // 关闭对话框
        this.addParamsDialogVisible = false
        // 重新发送请求刷新页面
        this.getTabsParams()
      })
    },
    // 关闭添加参数/添加属性对话框回调函数
    addParamsDialogVisibleClose() {
      // 重置表单
      this.$refs.addParamsDialogVisibleFormRef.resetFields()
    },
    // 编辑参数按钮
    paramsEditBtn(scope) {
      // 当前属性ID
      this.editParamsDialogVisibleForm.attrId = scope.attr_id
      // 当前属性值
      this.editParamsDialogVisibleForm.attr_name = scope.attr_name
      // 显示修改动态参数/静态属性对话框
      this.EditParamsDialogVisible = true
    },
    // 修改动态参数/添加属性
    editParamsOk() {
      // 表单预验证
      this.$refs.editParamsDialogVisibleFormRef.validate(async vdate => {
        if (!vdate) return false
        const { data: res } = await this.$http.put(
          `categories/${this.getCateThreeID}/attributes/${this.editParamsDialogVisibleForm.attrId}`,
          {
            attr_name: this.editParamsDialogVisibleForm.attr_name,
            attr_sel: this.paramsActiveName
          }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 提示
        this.$message.success(res.meta.msg)
        // 关闭对话框
        this.EditParamsDialogVisible = false
        // 重新发送请求渲染页面
        this.getTabsParams()
      })
    },
    // 删除参数
    async removeParamsBtn(scope) {
      console.log(scope)
      const resConfirm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (resConfirm !== 'confirm') return this.$message.info('已取消删除')
      // 发送请求
      const { data: res } = await this.$http.delete(
        `categories/${this.getCateThreeID}/attributes/${scope.attr_id}`
      )
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提示
      this.$message.success(res.meta.msg)
      // 重新发送请求刷新页面
      this.getTabsParams()
    },
    // 显示文本输入框
    showInput(scope) {
      console.log(scope)
      // 切换成文本输入框
      scope.paramsInputVisible = true
      // 显示文本输入框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本输入框失去焦点或按下回车触发
    paramsHandleInputConfirm(scope) {
      if (scope.paramsInputValue.trim().length === 0) {
        scope.paramsInputValue = ''
        return
      }
      // 添加值
      scope.attr_vals.push(scope.paramsInputValue)
      scope.paramsInputValue = ''
      // 切换成按钮
      scope.paramsInputVisible = false
      // 发送请求
      this.getEditParams(scope)
    },
    // 点击关闭Tag标签回调函数
    paramsTagClose(i, scope) {
      console.log(scope)
      // 删除
      scope.attr_vals.splice(i, 1)
      // 发送请求
      this.getEditParams(scope)
    },
    // 编辑提交参数请求
    async getEditParams(scope) {
      const { data: res } = await this.$http.put(
        `categories/${this.getCateThreeID}/attributes/${scope.attr_id}`,
        {
          attr_name: scope.attr_name,
          attr_sel: this.paramsActiveName,
          attr_vals: scope.attr_vals.join(' ')
        }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    }
  },
  computed: {
    isDisabled() {
      if (this.paramsCascaderValue.length !== 3) {
        return true
      }
      return false
    },
    // 获取三级分类ID
    getCateThreeID() {
      if (this.paramsCascaderValue.length === 3) {
        return this.paramsCascaderValue[this.paramsCascaderValue.length - 1]
      }
      return null
    },
    // 添加参数/添加属性对话框标题
    addParamsTitle() {
      if (this.paramsActiveName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 0 5px;
}

// input
.input-new-tag {
  width: 100px;
}
</style>
